package com.itheima.controller;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.R;

import com.itheima.pojo.dto.dishDto.DishAddDto;

import com.itheima.pojo.dto.dishDto.DishUpdateDto;
import com.itheima.pojo.vo.dishVo.DishByPageVo;
import com.itheima.pojo.vo.dishVo.GetDishByIdVo;
import com.itheima.pojo.vo.dishVo.GetDishVo;


import com.itheima.service.DishService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * @author tcotk
 */
@RestController
public class DishController {
    @Resource
    private DishService service;


    @PostMapping("/dish")
    @Transactional
    public R<String> add(@RequestBody DishAddDto dish) {

        String id = IdUtil.getSnowflakeNextIdStr();
        dish.setId(id);

        boolean result = service.add(dish);

        if ( result) {
            return R.success("新增菜品成功");
        }
        return R.error("新增菜品失败");
    }

    @PutMapping("/dish")
    @ResponseBody

    public R<String> update(@RequestBody DishUpdateDto dish) {
        boolean result = service.update(dish);

        if (result ) {
            return R.success("修改菜品成功");
        }
        return R.error("修改菜品失败");
    }

    @DeleteMapping("/dish")

    public R<String> delete( String[] ids) {
        boolean result = service.delete(ids);

        if (result ) {
            return R.success("删除菜品成功");
        }
        return R.error("删除菜品失败");
    }

    @PostMapping("/dish/status/{num}")
    public R<String> status(@PathVariable("num")int num,@RequestParam String[] ids) {
        boolean result = service.status(num,ids);
        if (result) {
            return R.success("修改菜品成功");
        }
        return R.error("修改菜品失败");
    }

    @GetMapping("/dish/list")
    public R<Object> selectAll() {
        List<GetDishVo> list = service.selectAll();
        return R.success(list);

    }

    @GetMapping("/dish/{id}")
    public R<Object> selectById(@PathVariable String id) {
        GetDishByIdVo getDishByIdVo = service.selectById(id);

        return R.success(getDishByIdVo);
    }

    @GetMapping("/dish/page")
    public R<Map<String,Object>> selectByPage(String name, Integer page, Integer pageSize) throws ParseException {
        List<DishByPageVo> list = service.selectByPage(page,pageSize,name);

         Integer total=(page-1)*pageSize;
        Map<String, Object> map = new HashMap<>();
        map.put("records", list);
        map.put("total", total);
        map.put("size", pageSize);
        map.put("current", page);
        map.put("optimizeCountSql", true);
        map.put("hitCount", false);
        map.put("countId", null);
        map.put("maxLimit", null);
        map.put("searchCount", true);
        map.put("pages", 20);
        return R.success(map);
    }


}
